package router

import (
	"fmt"
	"imageConvert/pkg/aop"
	"imageConvert/pkg/static"
	"imageConvert/web"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

const CovertImagePath = "./tmpFile/convert"

func InitRouter(p ...int) {
	os.RemoveAll(CovertImagePath)
	os.MkdirAll(CovertImagePath, os.ModeDir)

	gin.SetMode("release")
	g := gin.New()
	g.Use(aop.Recovery())

	g.Use(static.Serve("/", static.EmbedFolder(web.Static, ".")))
	g.NoRoute(func(c *gin.Context) {
		data, err := web.Static.ReadFile("index.html")
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		c.Data(http.StatusOK, "text/html; charset=utf-8", data)

		//if c.Request.URL.Path == "/" || c.Request.URL.Path == "" {
		//	//默认跳转到图片处理
		//	c.Redirect(http.StatusMovedPermanently, "/image")
		//} else {
		//	c.String(http.StatusNotFound, "404 Not Found Page")
		//}

	})

	apiImageRouter(g.Group("api/image"))

	httpPort := ":3166"
	if len(p) > 0 {
		httpPort = fmt.Sprintf(":%d", p[0])
	}
	g.Run(httpPort)
}
